import { Check, Mic, Pause, Play } from "lucide-solid";
import { createSignal, Show } from "solid-js";
import Button from "@/components/Button";
import useAudioRecorder from "@/hooks/audio-recorder";
import useKeysPress from "@/hooks/keys-press";

export default function AudioRecorderView() {
  document.title = "Audio Recorder";

  const [audioUrl, setAudioUrl] = createSignal<string | undefined>(undefined);

  const audio = useAudioRecorder({
    onOk(audio) {
      const url = URL.createObjectURL(audio);
      setAudioUrl(url);
    },
  });

  const handleClick = () => {
    switch (audio.status()) {
      case "inactive":
        audio.start();
        setAudioUrl(undefined);
        break;
      default:
        audio.stop();
        break;
    }
  };

  const handlePause = () => {
    switch (audio.status()) {
      case "recording":
        audio.pause();
        break;
      case "paused":
        audio.resume();
        break;
    }
  };

  const keys = useKeysPress({
    key1: "m",
    key2: "n",
    onAllPress: handleClick,
  });

  return (
    <div>
      <div class="p-4 flex gap-4">
        <Button shape="circle" variant="outline" onClick={handleClick}>
          <Show when={audio.status() === "inactive"} fallback={<Check size="18px" />}>
            <Mic size="18px" />
          </Show>
        </Button>
        <Button shape="circle" variant="outline" onClick={handlePause} disabled={audio.status() === "inactive"}>
          <Show when={audio.status() === "recording"} fallback={<Play size="18px" />}>
            <Pause size="18px" />
          </Show>
        </Button>
        <Show when={audioUrl()}>
          <audio controls src={audioUrl()}>
            <track kind="captions" />
          </audio>
        </Show>
      </div>
      <div>
        <small>
          点击按钮或者同时按下 <kbd>{keys.key1}</kbd>+<kbd>{keys.key2}</kbd> 键
          {audio.status() === "inactive" ? "开始" : audio.status() === "recording" ? "完成" : "xx"}
          录音 ({audio.status()})
        </small>
      </div>
    </div>
  );
}
